-- SPDX-License-Identifier: GPL-3.0-or-later
---@class EndLessPractice: Object
local WdtxObj = class("WdtxObj")
local Story = require "packages/wdtx/Story"
local Box = require "packages/wdtx/Box"
local Map = require "packages/wdtx/Map"
local Shop = require "packages/wdtx/Shop"
local Battle = require "packages/wdtx/Battle"
local OtherEvent = require "packages/wdtx/OtherEvent"
local WU = require "packages/wdtx/WUltiity"
local WD = require "packages/wdtx/WdtxData"
function WdtxObj:initialize(player,data)
  self.room = Fk:currentRoom()
  self.player = player

  self.storyid = data.storyid
  self.endstoryid = data.endstoryid

  self.upcardcfg = data.upcards
  self.costcards = data.costcards
  self.uptmpcards = {}
  self.costupcard = 7

  self.batsetmentdata = data.batsetmentdata

  self:initStoryData(data.storyinfo)
  self:initShopData(data.shopdata)
  self:initBoxData(data.boxdata)
  self:initBattleData(data.battledata)
  self:initOtherEventData(data.othereventdata)
  self:initMapData(data.mapdata)
end

function WdtxObj:initOtherEventData(othereventdata)   --初始化其他事件数据
  self.othereventobj = OtherEvent:new(self.player,othereventdata,self)
end

function WdtxObj:initBattleData(battledata)   --初始化战斗数据
  self.battleobj = Battle:new(self.player,battledata,self)
end

function WdtxObj:initBoxData(boxdata)   --初始化宝箱数据
  self.boxobj = Box:new(self.player,boxdata,self)
end

function WdtxObj:initShopData(shopdata)   --初始化商店数据
  self.shopobj = Shop:new(self.player,shopdata,self)
end

function WdtxObj:initStoryData(storyinfo)   --初始化剧情数据
  self.storyobj = Story:new(self.player,storyinfo,self)
end

function WdtxObj:initMapData(mapdata)   --初始化地图数据
  self.mapobj = Map:new(self.player,mapdata,self)
end

function WdtxObj:getGold(value)   --获得金币
  self.room:addPlayerMark(self.player,"@gold_num",value)
  self.room:doBroadcastNotify("ShowToast", Fk:translate(self.player.general) .."获得金币+"..value)
end

function WdtxObj:costGold(value,reason)   --花费或丢失金币
  reason = reason or ""
  self.room:removePlayerMark(self.player,"@gold_num",value)
  self.room:doBroadcastNotify("ShowToast", Fk:translate(self.player.general) .."失去金币-"..value.."。"..reason)
end

function WdtxObj:changeSoldier(player)   --敌对人机死亡转为小兵且清除技能
  local room = self.room
  player:bury()
  local generalskills = player:getAllSkills()
  room:changeHero(player, "blank_shibing")
  if player.role ~= "rebel" then
    room:setPlayerProperty(player, "role", "rebel")
  end
  if #generalskills > 0 then
    local loseskills = ""
    for _,s in ipairs(generalskills) do
      loseskills = loseskills.."-"..s.name.."|"
    end
    room:handleAddLoseSkills(player, loseskills, nil, false)
  end
end

function WdtxObj:getRwdByBatSetment(num)   --战斗结算卡牌概率
  local batsetmentdata = self.batsetmentdata[self.storyid]
  local weight_cards = WU:getItemsByWeight(num,batsetmentdata.weight)
  local cardsdata = {}
  for _,t in ipairs(weight_cards) do
    local cardname = WU:getItemByWeight(batsetmentdata[t],cardsdata)
    if not cardsdata[cardname] then
      cardsdata[cardname] = 1
    else
      cardsdata[cardname] = cardsdata[cardname] + 1
    end
  end
  return cardsdata
end

--洗牌
function WdtxObj:shuffCards(include_cost) 
  local room,player = self.room,self.player
  local cds = {}
  local discs_pile = player:getPile("self_discs")
  if #discs_pile > 0 then
    table.insertTable(cds,discs_pile)
  end
  if include_cost then
    local cost_pile = player:getPile("self_cost")
    if #cost_pile > 0 then
      table.insertTable(cds,cost_pile)
    end
  end
  
  if #cds > 0 then
    room:moveCards({
      from = player.id,
      ids = cds,
      fromArea = Card.PlayerSpecial,
      -- to = player.id,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      proposer = player.id,
      skillName = "#wdtx_rule",
    })
    -- room:delay(300)
    player:addToPile("self_draws", cds, true, "#wdtx_rule")
  end
end

--添加初始卡组
function WdtxObj:addInitCardsToArea(needpiles) 
  local cards = self:findCards(needpiles,self.room.void)
  self:inputPipleByGet(cards,"self_draws")  --游戏开始获得卡组加入私人牌堆
end
--从无牌区域找卡组needpiles配置中选num张牌加入卡组
function WdtxObj:addCardsFromVoid(needpiles,num,extselect) 
  local room = self.room
  local cards = self:findCards(needpiles,self.room.void)
  local getstr = "你可以从"..#cards.."张卡牌里选择<font color='#90EE90'><b>最多"..num.."张牌</b></font>加入卡组。"
  local btns = {"OK"}
  if extselect then
    getstr = getstr.."或者获得一定的<font color='yellow'><b>金币</b></font>。"
    table.insert(btns,"selgold:::"..math.random(6,9)) 
    if self.player:isWounded() then
      getstr = getstr.."或者恢复<font color='green'><b>2</b></font>点体力。"
      table.insert(btns,"rec_hp:::".."2")
    end
    if self.player:getMark("@gold_num") >= self.costupcard then
      getstr = getstr.."或者<font color='red'><b>花费"..self.costupcard.."金币升级1张卡牌</b></font>。"
      table.insert(btns,"uplvcards:::"..self.costupcard)
    end
  end
  local reply = room:askForCustomDialog(self.player,"#wdtx_rule","packages/wdtx/qml/DialogCardsChcBox.qml",{"#wdtx_rule",getstr,"hxfc_author",cards,1,num,btns})
  if reply ~= "" then
    reply = json.decode(reply)
    if extselect and reply.choice ~= "OK" then
      if string.startsWith(reply.choice,"selgold") then
        local npos = string.find(reply.choice,":%d")
        local nvalue = tonumber(string.sub(reply.choice,npos+1))
        self:getGold(nvalue) 
      elseif string.startsWith(reply.choice,"rec_hp") then
        local npos = string.find(reply.choice,":%d")
        local nvalue = tonumber(string.sub(reply.choice,npos+1))
        room:recover({who = self.player,num = nvalue,skillName = "#wdtx_rule"})
      elseif string.startsWith(reply.choice,"uplvcards") then
        self:costGold(self.costupcard,"花费"..self.costupcard.."金币升级了1张卡牌")
        self.costupcard = self.costupcard + 1
        self:upCardByPile(1)
      end
      return
    end
    if reply.cards and #reply.cards > 0 then
      self:inputPipleByGet(reply.cards,"self_draws") 
    end
  else
    return self:addCardsFromVoid(needpiles,num,extselect)
  end
end
--找牌组，找不到就印卡优化牌
function WdtxObj:findCards(needpiles,piles) 
  local obtain_cards = {}
  local value = 0
  for k,v in pairs(needpiles) do
    value = v + value
  end
  for _,cid in ipairs(piles) do
    local card = Fk:getCardById(cid)
    local remain_num = needpiles[card.name]
    if remain_num and remain_num > 0 then
      table.insert(obtain_cards,cid)
      value = value -1 
      needpiles[card.name] = needpiles[card.name] - 1
    end
    if value <= 0 then break end
  end
  if value > 0 then
    for cname,num in pairs(needpiles) do
      if num > 0 then
        for i = 1,num do
          local cid = self.room:printCard(cname, math.random(1,4), math.random(1,13)).id
          table.insert(obtain_cards,cid)
        end
      end
    end
  end
  return obtain_cards
end
--获取到的卡牌放进私人牌堆
function WdtxObj:inputPipleByGet(cards,pilename)
  local room = self.room
  if not cards or #cards == 0 then room:doBroadcastNotify("ShowToast","警告，没有获得的卡组") return end
  for _,cid in ipairs(cards) do
    local card = Fk:getCardById(cid)
    room:setCardMark(card,"card_owner",self.player.id)
    if self.costcards[card.name] then
      room:setCardMark(card,"@@costcard",-1)
    end
  end
  self.player:addToPile(pilename, cards, true, "#wdtx_rule")
end
--此模式抽卡接口
function WdtxObj:drawCards(num,pile)
  local room = self.room
  local draw_pipe = pile or self.player:getPile("self_draws")
  local min = math.min(num,#draw_pipe)
  if min == 0 then  
    return room:doBroadcastNotify("ShowToast","没牌可以抽了")
  elseif num >= #draw_pipe then
    room:doBroadcastNotify("ShowToast","牌堆见底")
  end
  local drawcards = self:drawCardsFromPile(min,pile)
  room:moveCards({
    from = self.player.id,
    ids = drawcards,
    fromArea = Card.PlayerSpecial,
    to = self.player.id,
    toArea = Card.PlayerHand,
    moveReason = fk.ReasonJustMove,
    proposer = self.player.id,
    skillName = "#wdtx_rule",
  })
end
--从私人牌堆获取随机卡牌
function WdtxObj:drawCardsFromPile(num,pile)
  local drawpiles = pile or self.player:getPile("self_draws")
  return table.random(drawpiles,num)
end
--从私人牌堆移除任意卡牌到Void清除该卡标记
function WdtxObj:removeCardsMarkToVoid(cids,needret)
  local room = self.room
  local retinfo = needret and {} or nil
  for _, cid in ipairs(cids) do
    local card = Fk:getCardById(cid)
    if next(card.mark) and self.upcardcfg[card.name] then
      -- local upnum = 0
      for m,v in pairs(card.mark) do
        if m ~= "card_owner" and v ~= 0 then
          room:setCardMark(card,m,0)
          if needret then
            retinfo[tostring(cid)] = 1           
          end
        end
      end
    end
  end
  return needret and retinfo or nil
end
--从私人牌堆移除任意卡牌到Void
function WdtxObj:removeCardsToVoid(num,isremove_mark,lefthuman,say,needret)
  local room = self.room
  local human = lefthuman or "hxfc_author"
  local getstr = say or "请选择最多"..num.."张牌移除"
  local removecards = {}
  local draws_area = self.player:getPile("self_draws")
  if #draws_area > 0 then
    table.insertTable(removecards,draws_area)
  end
  local disc_area = self.player:getPile("self_discs")
  if #disc_area > 0 then
    table.insertTable(removecards,disc_area)
  end
  local cost_area = self.player:getPile("self_cost")
  if #cost_area > 0 then
    table.insertTable(removecards,cost_area)
  end

  local cids
  if #removecards > 0 then
    local reply = room:askForCustomDialog(self.player,"#wdtx_rule","packages/wdtx/qml/DialogCardsChcBox.qml",{"#wdtx_rule",getstr,human,removecards,1,num,{"OK"}})
    if reply ~= "" then
      reply = json.decode(reply)
      if reply.cards and #reply.cards > 0 then
        cids = reply.cards
      end
    else
      return self:removeCardsToVoid(num,isremove_mark,lefthuman,say)
    end
  else
    -- error("没有卡牌")
    return false
  end

  local retinfo
  if isremove_mark then
    retinfo = self:removeCardsMarkToVoid(cids,needret)
  end
  local cardstr = ""
  for _,cid in ipairs(cids) do
    local card = Fk:getCardById(cid)
    cardstr = cardstr.."<font color='red'><b>"..Fk:translate(card.name).."</b></font>，"
  end
  room:moveCards({
    from = self.player.id,
    ids = cids,
    fromArea = Card.PlayerSpecial,
    toArea = Card.Void,
    moveReason = fk.ReasonJustMove,
    proposer = self.player.id,
    skillName = "#wdtx_rule",
  })
  room:doBroadcastNotify("ShowToast", Fk:translate(self.player.general) .."移除了"..cardstr)
  return retinfo,#cids
end
--获得可升级卡牌
function WdtxObj:getCanUpCards(cids)
  local upcards = {}
  if #cids == 0 then return upcards end
  for _,cid in ipairs(cids) do
    local card = Fk:getCardById(cid,true)
    local cfg = self.upcardcfg[card.name]
    if cfg then
      local mark_type = cfg.type
      local mark_name = cfg.mark
      local mark_max = cfg.max
      if mark_type == 1 then
        local markv = card:getMark(mark_name)
        if markv < mark_max then
          table.insert(upcards,cid)
        end
      elseif mark_type == 2 then --类型为2时候。标记为数组，每个标记只升级一次，标记数组总数要等于max
        local addv = 0
        for _,m in ipairs(mark_name) do
          addv = card:getMark(m) + addv
        end
        if addv < mark_max then
          table.insert(upcards,cid)
        end
      end
    end  
  end
  return upcards
end
--降级卡牌标记(临时升级后进入弃卡区域的效果)
function WdtxObj:removeCardMark(upcard,name)
  local room = self.room
  local cfg = self.upcardcfg[upcard.name]
  local mark_type = cfg.type
  local mark_name = cfg.mark
  local mark_value = cfg.v
  if mark_type == 1 then
    room:removeCardMark(upcard,mark_name,mark_value)
    return true
  elseif mark_type == 2 then --类型为2时候。标记为数组，每个标记只升级一次，标记数组总数要等于max
    for _,m in ipairs(mark_name) do
      if upcard:getMark(m) ~= 0 and name == m then
        room:removeCardMark(upcard,m,mark_value)
        return true
      end   
    end
  end
end
--设置卡牌升级标记（开宝箱，进卡牌商店场景）
function WdtxObj:setCardMark(upcard,setvalue,istmp)
  local room = self.room
  local cfg = self.upcardcfg[upcard.name]
  local mark_type = cfg.type
  local mark_name = cfg.mark
  local mark_value = setvalue <= cfg.max and setvalue or cfg.max
  if mark_type == 1 then
    room:setCardMark(upcard,mark_name,mark_value)
    if istmp then
      table.insert(self.uptmpcards,{id = upcard.id,mark = mark_name,v = mark_value})
    end
  elseif mark_type == 2 then --类型为2时候。标记为数组，每个标记只升级一次，标记数组总数要等于max
    for _,m in ipairs(mark_name) do
      if upcard:getMark(m) == 0 then
        room:setCardMark(upcard,m,1)
        if istmp then
          table.insert(self.uptmpcards,{id = upcard.id,mark = m,v = 1})
        end
      end   
    end
  end
end
--升级卡牌标记
function WdtxObj:upCardMark(upcard,istmp)
  local room = self.room
  local cfg = self.upcardcfg[upcard.name]
  local mark_type = cfg.type
  local mark_name = cfg.mark
  local mark_value = cfg.v
  if mark_type == 1 then
    room:addCardMark(upcard,mark_name,mark_value)
    if istmp then
      table.insert(self.uptmpcards,{id = upcard.id,mark = mark_name})
    end
  elseif mark_type == 2 then --类型为2时候。标记为数组，每个标记只升级一次，标记数组总数要等于max
    for _,m in ipairs(mark_name) do
      if upcard:getMark(m) == 0 then
        room:addCardMark(upcard,m,mark_value)
        if istmp then
          table.insert(self.uptmpcards,{id = upcard.id,mark = m})
        end
        break
      end   
    end
  end
end
--重置卡牌标记为0
function WdtxObj:resetCardMark(cards)
  local room = self.room
  for _, cid in ipairs(cards) do
    local card = Fk:getCardById(cid)
    if next(card.mark) then
      for m,v in pairs(card.mark) do
        if v ~= 0 then
          room:setCardMark(card,m,0)
        end
      end
    end
  end
end
--检测临时升级卡牌进入弃卡区后清除升级标记
function WdtxObj:checkUpTmpCards(cards)
  if #self.uptmpcards == 0 then return end
  local cur = 0
  while cur < #self.uptmpcards do
    cur = cur + 1
    local data = self.uptmpcards[cur]
    if table.contains(cards,data.id) then      
      local card = Fk:getCardById(data.id,true)
      local ret = self:removeCardMark(card,data.mark)
      if ret then
        table.remove(self.uptmpcards,cur)
      else
        error(string.format("卡牌移除临时升级标记失败", card.name))
      end
      cur = 0
    end
  end
end
--临时升级卡牌
function WdtxObj:upCardsByTmp(tmpcards)
  for _, cid in ipairs(tmpcards) do
    local card = Fk:getCardById(cid,true)
    self:upCardMark(card,true)
  end
end
--升级卡牌
function WdtxObj:upCardByPile(num,lefthuman,say)
  local room = self.room
  local human = lefthuman or "hxfc_author"
  local can_upcards = {}
  local draws_area = self.player:getPile("self_draws")
  if #draws_area > 0 then
    table.insertTable(can_upcards,draws_area)
  end
  local disc_area = self.player:getPile("self_discs")
  if #disc_area > 0 then
    table.insertTable(can_upcards,disc_area)
  end
  local cost_area = self.player:getPile("self_cost")
  if #cost_area > 0 then
    table.insertTable(can_upcards,cost_area)
  end
  local upcards = self:getCanUpCards(can_upcards)
  if #upcards == 0 then room:doBroadcastNotify("ShowToast","没有卡牌可升级") return end
  local getstr = say or "请选择最多"..num.."张牌升级"
  local reply = room:askForCustomDialog(self.player,"#wdtx_rule","packages/wdtx/qml/DialogCardsChcBox.qml",{"#wdtx_rule",getstr,human,upcards,1,num,{"OK"}})
  if reply ~= "" then
    reply = json.decode(reply)
    local upstr = ""
    if reply.cards and #reply.cards > 0 then
      for _,cid in ipairs(reply.cards) do
        local card = Fk:getCardById(cid,true)
        upstr = upstr.."<font color='green'><b>"..Fk:translate(card.name).."</b></font>，"
        self:upCardMark(card)
      end
    end
    room:doBroadcastNotify("ShowToast",Fk:translate(self.player.general).."升级了"..upstr)
    return
  else
    return self:upCardByPile(num)
  end
end
-------------------------------------------------------------------刷新剧情事件-------------------------------------------------------------------
function WdtxObj:setCurInfo(data)  
  self.storyobj:setCurInfo(data)
end
function WdtxObj:refreshStory(evts)  
  self.storyobj:refreshStory(evts)
end
function WdtxObj:getCurProgress()
  return self.storyobj:getCurProgress()
end
--添加新的剧情
function WdtxObj:addNewStory(evtname,dialog,pos)
  pos = pos or 2 --没有值默认为下一个剧情事件，位置是2
  self.storyobj:addNewStory(evtname,dialog,pos)
end
--添加子剧情
function WdtxObj:addSubDialog(subdialog,rootpos,subpos)
  subpos = subpos or 2
  rootpos = rootpos or 1 --没有值默认为当前剧情事件，位置是1
  self.storyobj:addSubDialog(subdialog,rootpos,subpos)
end
--执行其他事件
function WdtxObj:exeOtherEvent(reply)
  self.othereventobj:exeOtherEvent(reply)
end
--执行其他事件
function WdtxObj:deployEnemys(data)
  self.battleobj:deployEnemys(data)
end
--删除宝箱相同的技能表
-- function WdtxObj:removeBoxSameSkills(skills)
--   self.boxobj:removeSameSkills(skills)
-- end
-- --删除商店相同的技能表
-- function WdtxObj:removeShopSameSkills(skills)
--   self.shopobj:removeSameSkills(skills)
-- end
--删除宝箱、商店相同的技能表
function WdtxObj:removeSameSkills(skills)
  self.boxobj:removeSameSkills(skills)
  self.shopobj:removeSameSkills(skills)
end
--执行剧情事件（在diolog.qml按下选择按钮后第一时间执行这个回调，执行完后才从剧情的事件列表里events和dialog数据第一个位置的数据出栈）
function WdtxObj:extEvent(reply)
  local room = self.room
  local selchcinx,selchc,chcevent = reply.selchcinx,reply.selchc,reply.chcevent
  local evt = self.storyobj:getEvent()
  if evt == Map.NorMonsterStr or evt == Map.EliteMonsterStr or evt == Map.BossStr then
    -- if evt == Map.BossStr then
    --   self.battleobj:readyBattle(evt)
    --   self:setStoryStatus(Story.StatusFight)
    -- else
    --   self:setStoryStatus(Story.StatusChoice)
    -- end
    self.battleobj:readyBattle(evt)
    self:setStoryStatus(Story.StatusFight)
  elseif evt == Map.AddMaxHp then
    room:setPlayerProperty(self.player, "maxHp", self.player.maxHp+1)
    self:setStoryStatus(Story.StatusChoice)
  elseif evt == Map.BoxStr then
    self:openBox()
    self:setStoryStatus(Story.StatusChoice)
  elseif evt == Map.ShopStr then
    self:enterShop()
    self:setStoryStatus(Story.StatusChoice)
  elseif evt == Map.OtherEventsStr then
    self:exeOtherEvent(reply)
    -- self:setStoryStatus(Story.StatusChoice)
  elseif evt == Map.RestStr then
    if chcevent == 1 then
      self:addSubDialog({
        dialog = {{talkers={1,self.player.general,2,"hxfc_author"},say="路途艰辛，我看得歇会。"}},
        choices = {"回满体力","遗忘1张卡","升级1张卡"},
        eventchc = {2,2,2}
      },1,2)
    else
      if selchc == "回满体力" then
        if self.player:isWounded() then
          room:recover({who = self.player,num = self.player:getLostHp(),skillName = "#wdtx_rule"})
        end
        -- self:upCardByPile(1)
      elseif selchc == "遗忘1张卡" then
        self:removeCardsToVoid(1)
      elseif selchc == "升级1张卡" then
        self:upCardByPile(1)
      end
    end
    self:setStoryStatus(Story.StatusChoice)
  elseif evt == "beginAdventure" then
    if selchc == "技能4选1" then
      local skills = table.random(WD:getInitSkillsData(),4)
      local chs = room:askForChoices(self.player,skills,1,1,"#wdtx_rule","#wdtx_rule",false,true)
      self:removeSameSkills(chs)
      local str = table.concat(chs,"|")
      room:handleAddLoseSkills(self.player, str, nil, false)
    elseif selchc == "升级2张牌" then
      self:upCardByPile(2)
    elseif selchc == "移除3张牌" then
      self:removeCardsToVoid(3)
    elseif selchc == "获得15金币" then
      self:getGold(15)
    elseif selchc == "从4张牌选2张加入卡组" then
      -- self:addCardsFromVoid({wdtx__slash=3,wdtx_thunder__slash=1,wdtx_fire__slash=1,wdtx__jink=2,},3)
      local getcardsdata = self:getRwdByBatSetment(4)
      self:addCardsFromVoid(getcardsdata,2)
    end
    self:setStoryStatus(Story.StatusChoice)
  else
    if selchc == "离开" then 
      if reply.cid and reply.cid ~= 0 then
        self:resetCardMark({reply.cid})
      end
      self:setStoryStatus(Story.StatusChoice)
      return 
    end
    if string.startsWith(evt,"getcd") and reply.cid and reply.cid ~= 0 then
      self:inputPipleByGet({reply.cid},"self_draws")
    end
    self:setStoryStatus(Story.StatusChoice)
  end
  -- if not self.selagain then
  --   self.selagain = true
  --   local chc = {"技能6选2","升级2张牌","获得25金币","移除3张牌","从6张牌选2张加入卡组"}
  --   table.removeOne(chc,selchc)
  --   self:addNewStory("beginAdventure",{
  --     {dialog = {{talkers={1,"hxfc_author",2,self.player.general},say="前路漫漫，再选择一次。"}},
  --       choices = chc,
  --       eventchc = {1,1,1,1}
  --     }
  --   },2)
  -- end
end
function WdtxObj:startDialogStory(eventname,dialogcontent,startindex,chsindex)   --开始对话剧情
  local player = self.player
  local room = player.room
  local reply = room:askForCustomDialog(player,"author_says","packages/wdtx/qml/DialogBox.qml",
  { Map.Translate[eventname] or Fk:translate(eventname),
    dialogcontent,
    startindex,
    chsindex
  })

  if reply == "" then
    return self:startDialogStory(eventname,dialogcontent,startindex,chsindex)
  end
  reply = json.decode(reply)
  -- p(reply)
  -- p(dialogcontent)
  -- dbg()
  if reply.chcevent and reply.chcevent > 0 and reply.selchcinx then
    self:extEvent(reply)
    local status = self:getStoryStatus()
    if status == Story.StatusFight then return end
  end
  
  if reply.startpos + 1 >= #dialogcontent then
    -- print("==========对话结束============")
    -- dbg()
    self:setCurInfo({startpos = 0,selchcinx = 0})
    self:setStoryStatus(Story.StatusEnd)
    return 
  end
  self:setCurInfo({startpos = reply.startpos+1,selchcinx = 0})
  self:setStoryStatus(Story.StatusContinue)
  return
end

function WdtxObj:storyEnd()   --剧情是否结束
  local room = self.room
  local player = self.player
  if self.storyid < self.endstoryid then
    room:setPlayerProperty(player, "maxHp", player.maxHp+1)
    room:setPlayerProperty(player, "hp", player.hp+1)
    self.storyid = self.storyid + 1
    self.battleobj:initBattleData()
    self.boxobj:initBoxSkills()
    self.shopobj:initShopSkills()
    self.othereventobj:initEventData()
    self.mapobj:initMapData()
    self:openMapBox()
    return false
  else
    room:doBroadcastNotify("ShowToast", "游戏章节结束，敬请期待")
    room:gameOver("lord")
    return true
  end
end

function WdtxObj:continueStory(nextstartpos,nextchsindex)   --继续剧情
  if not self.storyobj:getEvent() and self:storyEnd() then return end

  if self.storyobj:getEvent() and self.storyobj:getDialog() then
    self:startDialogStory(self.storyobj:getEvent(),self.storyobj:getDialog(),nextstartpos,nextchsindex)
  end
  
  local status = self:getStoryStatus()
  -- p(status)
  -- dbg()
  if status ~= Story.StatusContinue then
    self:removeCurStory() --删除当前剧情
    if not self.storyobj:getEvent() and status ~= Story.StatusFight then --结束生成地图数据跳到剧情结束
      self:openMapBox()
    end
  end
  if status == Story.StatusEnd then
    return self:nextStory()
  elseif status == Story.StatusFight then
    self:drawCards(4)
    return
  elseif status == Story.StatusObserve then
    return
  else
    local curinfo = self.storyobj:getCurInfo()
    -- p(curinfo)
    -- dbg()
    return self:continueStory(curinfo.startpos,curinfo.selchcinx)
  end
end

function WdtxObj:nextStory()   --下一个剧情
  self:setStoryStatus(Story.StatusNormal)
  return self:continueStory(0,0)
end
function WdtxObj:defeatAllRobots()   --击杀所有人机后
  local player,room = self.player,self.room
  local gold = math.random(7,9)
  if self.storyid > 1 then
    gold = gold + math.floor(gold * (self.storyid - 1) * 0.15)
  end
  -- player:throwAllCards("hej")
  local discards = {}
  local costarea = player:getPile("self_cost")
  local allcards = player:getCardIds("hej")
  if #allcards > 0 and #costarea == 0 then
    discards = allcards
  else
    if #costarea > 0 then
      table.insertTable(discards,costarea)
    end
    if #allcards > 0 then
      table.insertTable(discards,allcards)
    end
  end
  if #discards > 0 then
    room:throwCard(discards,"#wdtx_rule",player,player)
  end
  if #room.alive_players == 1 then
    if room.current == player then
      player:gainAnExtraTurn(true,"#wdtx_rule")
    else
      self:shuffCards(true)
    end
  else
    player:gainAnExtraTurn(true,"#wdtx_rule")
  end
  --其他事件奖励
  local evt = self.othereventobj:isTriEvent()
  if evt then
    self.othereventobj:extEventRwd(evt)
  end
  local getcardsdata = self:getRwdByBatSetment(4)
  self:addCardsFromVoid(getcardsdata,1,true)
  local curinfo = self.storyobj:getCurInfo()
  --结算奖励
  if curinfo.startpos and curinfo.startpos > 0 then --其他事件发生战斗额外给金币然后重置新的剧情索引
    gold = gold + gold
    curinfo.startpos = 0
    curinfo.selchcinx = 0
  end
  self:getGold(gold)
  
  if not self.storyobj:getEvent() then
    if self:getCurProgress() > 0 then --看是否还有地图数据，如果有继续看地图。如果没有在boss节点结束
      self:openMapBox()
    end
    self:continueStory(curinfo.startpos or 0,curinfo.selchcinx or 0)
  else
    self:continueStory(curinfo.startpos or 0,curinfo.selchcinx or 0)
  end

  room.logic:getCurrentEvent():findParent(GameEvent.Turn):shutdown()
end

function WdtxObj:getStotyID()   --获得剧情id
  self.storyobj:getID()
end

function WdtxObj:setStotyID(id)   --设置剧情id
  self.storyobj:setID(id)
end

function WdtxObj:setStoryStatus(status)   --设置剧情状态
  self.storyobj:setStatus(status)
end

function WdtxObj:getStoryStatus()   --获得剧情状态
  return self.storyobj:getStatus()
end

function WdtxObj:removeCurStory()   --删除当前剧情事件
  return self.storyobj:removeStory()
end
-------------------------------------------------------------------刷新剧情事件-------------------------------------------------------------------

-------------------------------------------------------------------进入商店-------------------------------------------------------------------
function WdtxObj:enterShop()   --商店可以购买（卡牌，技能....）
  self.shopobj:enterShop()
end
-------------------------------------------------------------------进入商店-------------------------------------------------------------------

-------------------------------------------------------------------开宝箱处理-------------------------------------------------------------------
function WdtxObj:openBox(boxtype)   --打开宝箱可能获得（卡牌，技能....）
  self.boxobj:openBox(boxtype)
end
-------------------------------------------------------------------开宝箱处理-------------------------------------------------------------------
-------------------------------------------------------------------打开地图处理-------------------------------------------------------------------
function WdtxObj:openMapBox()
  self.mapobj:openMapBox()
end
-------------------------------------------------------------------打开地图处理-------------------------------------------------------------------

function WdtxObj:curPlayerisTriEvent(general)  
  return self.othereventobj:curPlayerisTriEvent(general)
end
return WdtxObj
